//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');
var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
var spuId = wx.getStorageSync('spuId');

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

var onemoreFlag = false;
var goodOrders = new Array();
var createTime = util.formatTime(new Date()).toString();

Page({

  detailList: [],    //初始化店铺详情
  cateGorylist: [],   //初始化店铺分类list
  goodslist: [],      //初始化商品list

  data: {
    textId: '',
    feekbackState: "",
    carts: 0,
    numm:0,
    showModal: false,
    showModall: false,
    showModalll: false,
    zon:0,
    zong: 0.0,
    danjia: 0,
    pai: 0,
    area: [],
    list: [],
    gwclist: [],
    ping:[],
    shangjiadizhi:'',
    tel:'',
    deliveryTimeType:'',
    deliveryCost:'',
    deliveryFee:'',
    outCostFree:'',
    goodOrders: goodOrders,
    num:0,
    goodslist: [],
    goodsDetails:' ',           //商品详情
    categoryId : '',            //分类id
    goodsDetails_num:'',        //详情购物车数量
    imgUrls: [],
    feekbackListCon : [],
    indicatorDots: false,
    autoplay: true,
    interval: 2500,
    duration: 1000,
    currentTab : '0',
    showCancelArea: false
  },
  onLoad: function (options) {

    var that = this;
    var onemoreFlag = app.globalData.selectCondition;

    

    if (onemoreFlag == true){
      that.setData({
        showModalll:true
      })
    }

    var openId = wx.getStorageSync('openId');     //用户openId获取
    var phone = wx.getStorageSync('phone');       //用户phone获取
    var userId = wx.getStorageSync('userId');     //用户userId获取
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取

    if (openId != '') {
      that.setData({
        openId: openId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }

    /**
     * 判断是否有手机号
     */
    if (phone == '') {
      that.setData({
        phone: ''
      })
    } else {
      that.setData({
        phone: phone
      })
      that.gucl();
    }

    if (userId != '') {
      that.setData({
        userId: userId
      });
    }

    if (userInfo != '') {
      that.setData({
        userInfo: userInfo
      });
    }
  

    //显示加载动画
    that.setData({
      hiddenLoading: false
    });

    that.initHeght();                   //初始化页面高度
    that.shopShopDetail();              //初始化店铺详情
    that.shopGoodsCategory();           //初始化店铺分类
    that.countfeekbackHeight();         //初始化评价高度

    console.log(options);
    var spuId = options.spuId;
    if (spuId != '') {
      that.alertDetail(spuId)
    }

    /** 
     * 获取系统信息 
     */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          hiddenLoading: true
        });
      }
    });

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openIdFlag = wx.getStorageSync('openId');     //用户openId获取
    var phoneFlag = wx.getStorageSync('phone');       //用户phone获取
    //判断openId是否存在
    if (openIdFlag != '') {
      that.setData({
        openId: openIdFlag,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }
    //判断手机号是否存在
    if (phoneFlag != '') {
      that.setData({
        phone: phoneFlag
      });
      that.gucl();                        //初始化购物车
    } else {
      that.setData({
        phone: ''
      });
    }
  },
  /**
  * 手机号授权方式
  */
  getPhoneNumberF: function (res) {
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
            wx.showToast({
              title: '登录成功',
              icon: 'none',
              duration: 2000,
              mask: true
            });
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    } else {
      wx.showToast({
        title: '授权后即可购买',
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },
  /**
   * 解密用户登录完成后的url (用户手机号)
   */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;

          that.setData({
            phone: phone
          })
          wx.setStorageSync('phone', phone);
          that.reginPhoneOpenid(phone);
        } else {
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //表单提交
  reginPhoneOpenid: function (userPhone) {
    var that = this;

    var nickName = that.data.userInfo.nickName;     //	昵称
    var avatarUrl = that.data.userInfo.avatarUrl;   //用户头像
    var gender = that.data.userInfo.gender;         //性别1为男，0为女
    var city = that.data.userInfo.city;             //城市
    var country = that.data.userInfo.country;       //国家
    var province = that.data.userInfo.province;     //省

    wx.request({
      url: apiHost + "xcx/login/reg",
      data: {
        // openId: 'olGet4mNKn1FeKEvSrGiMuY6v3ZB',
        openId: that.data.openId,
        yunId: yunId,
        userPhone: userPhone,
        nickName: nickName,
        avatarUrl: avatarUrl,
        gender: gender,
        city: city,
        country: country,
        province: province
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res)
        if (res.data.code == '10004') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: res.data.msg
          })
        }
        if (res.data.code == '10000') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: '　'
          })
        } else {
          that.setData({
            is_code: (!that.data.is_phone),   //提示信息
            ts_msg: res.data.msg
          })
        }
      },
    });

  },
  //搜索商品
  search_btn :function(){
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../searchGoods/searchGoods'
    });
  },
  //商家详情
  shopDetail :function(){
    var that= this;
    //商家
    wx.request({
      url: apiHost + "/xcx/store/detail",
      data: {
        yunId: yunId,
        userId: that.data.userId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.setData({
            shangjiadizhi: res.data.data.address,
            tel: res.data.data.phone,
            deliveryTimeType: res.data.data.deliveryTimeType,
            deliveryCost: res.data.data.deliveryCost,
            deliveryFee: res.data.data.deliveryFee,
            outCostFree: res.data.data.outCostFree,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  //点击商品，弹出商品详情
  goodsDetail : function(e){
    var that = this;
    
    var spuId = e.currentTarget.dataset.toggle;
    
    that.alertDetail(spuId);//获取弹出商品详情
  },
  /**
   * 获取弹出商品详情
   */
  alertDetail: function (spuId){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    wx.request({
      url: apiHost + "/xcx/goods/alert/detail",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        spuId: spuId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          var GodDetail = res.data.data
          that.setData({
            goodsDetails: GodDetail,
            goodsDetails_num: GodDetail.shopCartCount,
            showModal: true,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading 
      }
    })
  },
  //商品详情 减数量
  Gd_minus :function(){
    var that = this;
    var num = that.data.goodsDetails_num
    if (num > 1){
      that.setData({
        goodsDetails_num: num - 1
      })
    }
  },
   //商品详情 加数量
  Gd_add: function () {
    var that = this;
    var num = that.data.goodsDetails_num
    that.setData({
      goodsDetails_num: num + 1
    })
  },
  //商品详情 加入购物车
  addCart_gd : function(e){
    var that = this;
    if (that.data.openId == '') {
      wx.navigateTo({
        url: '../login/login?openId=' + that.data.openId,
        success: function () {
          wx.hideLoading();   //隐藏加载loading
        },
      });
    }else{
      var that = this;
      var bianjidizhi = e.target.dataset.toggle;//获取的拼接
      var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
      var spuId = bianjidizhiList[0];
      var danjia = bianjidizhiList[1];
      var num = parseInt(bianjidizhiList[2]);
      that.addCart(spuId, num);//计算购物车数量
      that.setData({
        showModal: false,
      })
    }
  },
  //获取高度
  initHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query = wx.createSelectorQuery();
    var query2 = wx.createSelectorQuery();
    var shopHeight = "";
    var ZtabHeight = "";

    query2.select('#Ztab').boundingClientRect()
    query2.exec(function (res) {
      ZtabHeight = res[0].height;
    });

    //获取店铺头部高度
    query.select('#shop').boundingClientRect()
    query.exec(function (res) {
      shopHeight = res[0].height;

      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            SwBoxHeight: res.windowHeight - shopHeight - ZtabHeight 
          });
        }
      });
    });
  },
  //获取店铺详情
  shopShopDetail: function () {
    var that = this;

    //获取店铺详情
    wx.request({
      url: apiHost + "xcx/store/detail",
      data: {
        yunId: yunId  //测试云店主id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            detailList: res.data.data
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      },
    });
  },
  /**
   * 店铺分类
   */
  shopGoodsCategory: function () {
    var that = this;
    // 初始化加载店铺分类信息
    wx.request({
      url: apiHost + "xcx/category/list",
      data: {
        yunId: yunId  //测试云店主id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.shopCateIdGoods(res.data.data[0].id);//初始化分类，第一个分类下的商品
          that.setData({
            cateGorylist: res.data.data,
            categoryId: res.data.data[0].id
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      },
    });
  },
  /**
   * 分类下的商品
   * @param cateGoryId
   */
  shopCateIdGoods: function (cateGoryId) {

    var that = this;
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    // 微信请求（点击分类）
    wx.request({
      url: apiHost + "xcx/goods/list/condition",
      data: {
        openId: that.data.openId,
        categoryId: cateGoryId,
        yunId: yunId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          var goodsList1 = res.data.data.list;
          that.setData({
            goodslist: goodsList1,
            hiddenLoading: true
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
    });
  },
  /**
 * 获取商品评价列表
 * @param state 评价状态
 */
  feekbackList: function (state) {
    var that = this;
    that.setData({
      hiddenLoading: false
    });
    wx.request({
      url: apiHost + "xcx/goods/feedback/list",
      data: {
        yunId: yunId,
        state: state
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            feekbackListCon: res.data.data.list,
            hiddenLoading: true
          })
          if (that.data.feekbackListCon.length != 0) {
            that.countfeekbackHeight(); //初始化评价高度
          }
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
    });
  },
  //评价点击时间
  feekbackClick: function (e) {
    var that = this;
    var feekbackState = e.target.dataset.toggle;

    that.setData({
      feekbackState: feekbackState
    })
    that.feekbackList(feekbackState);
  },
  //计算评价列表高度
  countfeekbackHeight: function () {
    var that = this;
    /*获取指定元素高度*/
    var query1 = wx.createSelectorQuery();
    var shopHeight = "";

    query1.select('#shop').boundingClientRect()
    query1.exec(function (res) {
      shopHeight = res[0].height;

      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            evaluateHeight: res.windowHeight - shopHeight
          });
        }
      });
    });
  },
  //初始化购物车
  gucl: function (e) {

    var _this = this;
    //购物车列表
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/list",
      data: {
        yunId: yunId,
        openId: _this.data.openId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code
        var msg = res.data.msg

        if (code=="10000"){
          var countCarts = 0;
          var CartsList = res.data.data.list;

          //循环遍历所有购物车的数量
          for (var a = 0; a < CartsList.length; a++) {
            countCarts += CartsList[a].count
          }
          _this.setData({
            gwclist: CartsList,
            carts: countCarts
          });

          //总价
          var newList = _this.data.gwclist
          var newaa = 0
          for (var i = 0; i < newList.length; i++) {
            newaa += newList[i].count * newList[i].price
          }

          _this.setData({
            zong: newaa.toFixed(2),
          })

          var categoryId = _this.data.categoryId;

          if (categoryId != '') {
            _this.shopCateIdGoods(categoryId)
          }
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })

  },

  //结算
  jie: function () {
    var _this = this
    var newList = _this.data.gwclist
    var a = ''
    var json = '';
    var that = this;
    var flag = "index";
    //显示加载动画
    that.setData({
      hiddenLoading: false
    });
    goodOrders = new Array();
    for (var i = 0; i < newList.length; i++) {
      a = {
        spuId: newList[i].spuId,
        count: newList[i].count
      }
      goodOrders.push(a);
    }
    json = JSON.stringify(goodOrders);

    if (goodOrders.length>0){
      wx.navigateTo({
        url: '/pages/userOrder/confirm/confirm?goodOrders=' + json + "&yunId=" + yunId + "&openId=" + that.data.openId + "&createTime=" + createTime +"&flag="+flag,
      })
      _this.setData({
        goodOrders: json
      })
    }

    that.setData({
      hiddenLoading: true
    });

  },

  //单击改变分栏的显示状态
  backgroundClick: function (e) {
    var that = this;
    var categoryId1 = e.target.dataset.toggle; //获取点击分类框的id

    //设置分类id
    that.setData({
      categoryId: categoryId1
    });

    that.shopCateIdGoods(that.data.categoryId);//点击显示分类下对应的商品
  },



  /**
     ** 滑动切换tab
     */
  bindChange: function (e) {
    var that = this;
    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.target.dataset.current; //获取当前tab页数

    //  重新设置tab 页数
    that.setData({ currentTab: e.detail.current });

    if (currIndex == cateGorytab) {
      that.shopGoodsCategory();   //初始化店铺分类
    } else if (currIndex == feekbacTab) {
      that.feekbackList(that.data.feekbackState);        //初始化店铺评价
    } else if (currIndex == shopSetUptab) {
      that.shopDetail();                  //商家详情
    }
  },
  /**
   * 点击tab切换
   */
  swichNav: function (e) {
    var that = this;

    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.target.dataset.current  //获取当前tab页数


    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      if (currIndex == cateGorytab) {
        that.shopGoodsCategory();   //初始化店铺分类
      } else if (currIndex == feekbacTab) {
        that.feekbackList(that.data.feekbackState);        //初始化店铺评价
      } else if (currIndex == shopSetUptab) {
        that.shopDetail();                  //商家详情
      }
    }
    //  重新设置tab 页数
    that.setData({
      currentTab: e.target.dataset.current
    });
  },
  // 购物车的显示隐藏
  cart: function (e) {
    // if (openId == '') {
    //   wx.navigateTo({
    //     url: '../login/login?openId=' + openId,
    //     success: function () {
    //       wx.hideLoading();   //隐藏加载loading
    //     },
    //   });
    // }else{}
      var _this = this;
      var bianjidizhi = e.target.dataset.toggle;//获取的拼接
      var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
      var spuId = bianjidizhiList[0];
      var danjia = bianjidizhiList[1];
      var num = bianjidizhiList[2];

      _this.setData({
        textId: spuId
      })

      _this.setData({
        showModal: false,
        showModall: true,
        num: 1
      })
      _this.gucl();
      var count = _this.data.num
      _this.addCart(spuId, count)
    
  },
  // 数量的++
  add: function (e) {
    var that = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);

    var index = parseInt(e.target.dataset.index);
    that.setData({
      showModal: false,
      showModall: true,
      num: num + 1,
    })
    
    var count = that.data.num
    that.addCart(spuId, count);//计算购物车数量
  },
  /**
   * 计算购物车数量
   */
  addCart: function (spuId, count){
    var that = this;

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/xcx/userShoppingCart/add",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        spuId: spuId,
        count: count
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.gucl();
          var categoryId = that.data.categoryId;
          that.shopCateIdGoods(categoryId)
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //隐藏购物车的++
  addd:function(e){
    var _this = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");//以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)

    _this.setData({
      numm: parseInt(count)+1,
    })
    var count = _this.data.numm
    _this.addCart(spuId, count);//计算购物车数量
    
  },
  // 数量的--
  minus: function (e) {
    var _this = this;

    var bianjidizhi = e.target.dataset.toggle;//获取的拼接
    var bianjidizhiList = bianjidizhi.split(",");//以逗号截取
    var spuId = bianjidizhiList[0];
    var danjia = bianjidizhiList[1];
    var num = parseInt(bianjidizhiList[2]);
    var cartId = bianjidizhiList[3];

    _this.setData({
      num: num - 1,
    })
    var count = _this.data.num

    if (count == 0) {
      _this.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
    } else {
      _this.addCart(spuId, count);//计算购物车数量
    }
  },
  //隐藏购物车的--
  minuss:function(e){
    var _this = this
    var gou = e.target.dataset.toggle;//获取的拼接
    var gouList = gou.split(",");//以逗号截取
    var spuId = gouList[0];
    var price = gouList[1];
    var count = gouList[2];
    var cartId = gouList[3];
    var index = parseInt(e.currentTarget.dataset.index);
    var numm = parseInt(e.currentTarget.dataset.count)
    _this.setData({
      numm: parseInt(count) - 1,
    })
    var count = _this.data.numm

     if(count == 0 ){
       _this.removeShopCart(cartId);//如果等于0 直接删除当前商品购物车
     }else{   
       _this.addCart(spuId, count);//计算购物车数量
    }
  },

  //删除购物车（当前商品在购物车）
  removeShopCart: function (cartId){
    var that = this;
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/del",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        cartId: cartId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.gucl();
          var categoryId = that.data.categoryId;
          that.shopCateIdGoods(categoryId)
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },

  gouwuchez: function () {
    var _this = this
    _this.setData({
      showModalll: true
    })

  },
  //关闭购物车
  gouwuchezz: function () {
    var _this = this
    _this.setData({
      showModalll: false
    })
  },
  // 清空购物车
  qingkong: function () {
    var _this = this
    wx.request({
      url: apiHost + "/xcx/userShoppingCart/clear",
      data: {
        openId: that.data.openId,
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        // console.log(res)
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          _this.gucl();
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

      }
    })
  },

  /**
  * 字符串转json
  */  
  stringToJson : function (data){  
    return JSON.parse(data);  
  },

  /** 
  * json转字符串
  */  
  jsonToString : function (data) {
    return JSON.stringify(data);
  } ,
  /**
 * 隐藏模态对话框
 */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  /**
 * 用户点击右上角分享
 */
  onShareAppMessage: function (options) {

    var that = this;
    var goodsDetails = that.data.goodsDetails;

    console.log(goodsDetails)

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: goodsDetails.name,
      // desc: '最具人气的小程序开发联盟!',
      path: 'pages/index/index?spuId=' + goodsDetails.spuId,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log("转发成功之后的回调")
        }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log("用户取消转发")
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log("转发失败")
        }
      },
    }
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      // 此处可以修改 shareObj 中的内容
      shareObj.path = 'pages/index/index?spuId=' + goodsDetails.spuId;
    }
    // 返回shareObj
    return shareObj;
  },
  //按钮获取用户信息
  getUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          wx.setStorageSync('userId', userInfo_.unionId);
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          })
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  }

})
